<template>
  <!--  <h2>创建专题库</h2>-->
    <div class="app-container">
      <el-row :gutter="20">
        <el-col :span="4" :xs="24">
          <el-row ref="hMain">
            <el-col :span="24">
              <div class="head-container">
                <el-input v-model="typeName" placeholder="请输入名称" clearable  prefix-icon="el-icon-search"
                          style="margin-bottom: 20px" />
              </div>
              <el-row :gutter="10" class="mb8" v-show="isShowButton">
                <el-col :span="1.5">
                  <el-button type="primary" plain icon="el-icon-plus"
                             @click="treeHandleAdd" size="small" v-hasPermi="['archive:YqZhuanTi:add']">新增</el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button type="success" plain icon="el-icon-edit"
                             @click="treeHandleUpdate" size="small" v-hasPermi="['archive:YqZhuanTi:edit']">修改</el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button type="danger" plain icon="el-icon-delete"
                             @click="treeHandleDelete" size="small" v-hasPermi="['archive:YqZhuanTi:remove']">删除</el-button>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <div class="head-container" :style="{height:tableHeight+'px'}" style="overflow: auto">
            <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false"
                     :filter-node-method="filterNode" :default-expanded-keys="expandedkeys"
                     :current-node-key="currentNodekey" ref="tree" node-key="typeId" default-expand-all highlight-current
                     @node-click="handleNodeClick" :style="size">
              <template slot-scope="{ node, data }">
                <span class="span-ellipsis" :title="node.label" :style="size">{{ node.label }}</span>
              </template>
            </el-tree>
          </div>
        </el-col>

        <el-col :span="20" :xs="24" v-show="isShow" ref="hMain">
          <el-row :gutter="10" class="mb8">
            <el-button type="success" plain  @click="save" v-hasPermi="['archive:YqZhuanTi:edit']" >保存</el-button>
          </el-row>
          <div class="head-container" :style="{height:tableHeight+'px'}" style="overflow: auto">
            <el-tree ref="roleTree" v-model="userId" :data="roleTree" node-key="id" :props="defaultProp" @node-click="roleClick" :style="size" default-expand-all>
            </el-tree>
          </div>
        </el-col>

        <el-col :span="20" :xs="24" v-show="!isShow" class="empty">
          <el-empty :image-size="200"></el-empty>
        </el-col>
      </el-row>

      <!-- 添加/修改专题 -->
      <el-dialog :title="title" :visible.sync="open" width="30%" append-to-body :before-close="cancel">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="封面" prop="coverPath">
              <el-upload class="avatar-uploader" :action="uploadUrl" :headers="headers" :on-success="handleUploadSuccess"
                         :on-exceed="handleExceed" :limit="1"
                         :on-remove="handleRemove" :file-list="fileList" list-type="picture-card" accept=".jpeg, .png, .jpg"
              >
                <img v-if="dialogImageUrl" width="100%" :src="dialogImageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
          </el-form-item>
          <el-form-item label="专题名称" prop="typeName">
            <el-input placeholder="请输入专题名称" v-model="form.typeName"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" placeholder="请输入备注" v-model="form.remark" ref="textareaFormRef"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 添加/修改目录 -->
      <el-dialog :title="directoryTitle" :visible.sync="directoryOpen" width="30%" append-to-body :before-close="cancel">
        <el-form ref="directoryForm" :model="directoryForm" :rules="directoryFormRules" label-width="80px">
          <el-form-item label="目录名称" prop="typeName">
            <el-input placeholder="请输入目录名称" v-model="directoryForm.typeName"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" placeholder="请输入备注" v-model="directoryForm.remark" ref="directoryFormText"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitdirectoryForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>

  <script>

  import {
    addCode,
    deleteCode,
    getCodeDetail,
    getTree,
    removeFile,
    updateCode, deptUserTree
  } from "@/api/archive/bianyan/createTopicLibrary";
  import {getToken} from "@/utils/auth";
  import estimateTableHeight from "@/mixins/estimateTableHeight";
  import {deptTreeSelect} from "@/api/system/user";
  import axios from "axios";

  export default {
    name: "index",
    mixins: [estimateTableHeight], // 混入方法
    data() {
      return {
        deptOptions: undefined,
        //默认展开的树节点
        expandedkeys: [],
        //默认选中的树节点
        currentNodekey: "",
        defaultProps: {
          children: "children",
          label: "typeName"
        },
        typeName: undefined,
        queryParams: {},

        // 角色树
        roleTree: [],
        isShow: false, //是否显示右侧数据
        defaultProp: {
          children: "children",
          label: "label"
        },
        userId: undefined,
        userName: '',

        // 专题弹窗
        title: '',
        open: false,
        form: {
          typeName: undefined,
          remark: undefined
        },
        rules: {
          typeName: [
            { required: true, message: "专题名称不能为空", trigger: "blur" }
          ]
        },
        imageUrl: '',
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        uploadUrl: process.env.VUE_APP_BASE_API + "/archive/special/subject/upload", // 上传的图片服务器地址
        limit: 1,
        fileList: [],
        dialogImageUrl: '',

        // 目录弹窗
        directoryTitle: '',
        directoryOpen: false,
        directoryForm: {
          typeName: undefined,
          remark: undefined
        },
        directoryFormRules: {
          typeName: [
            { required: true, message: "目录名称不能为空", trigger: "blur" }
          ]
        },

        isShowButton: false,
        size: ''
      }
    },
    watch: {
      // 根据名称筛选部门树
      typeName(val) {
        this.$refs.tree.filter(val);
      },
    },
    created() {
      if (this.$store.getters.size == 'small') {
        this.size = 'font-size: 12px;'
      } else {
        this.size = 'font-size: 14px;'
      }
      this.getDeptTree()
      this.getDeptTreePost()
    },
    methods: {
      /** 查询部门下拉树结构 */
      getDeptTree() {
        getTree().then(response=>{
          this.deptOptions = response.data
          if (this.deptOptions.length > 0) {
            this.currentNodeKey = this.deptOptions[0].typeId;
            this.expandedkeys.push(this.deptOptions[0].typeId);
            this.$nextTick(() => {
              this.$refs.tree.setCurrentKey(this.deptOptions[0].typeId)
            })
            // 专题id
            this.queryParams.typeId = this.deptOptions[0].typeId
            // 父级id
            this.queryParams.parentId = this.deptOptions[0].parentId
            // 专题名称
            this.queryParams.typeName = this.deptOptions[0].typeName
            this.isShowButton = true
          }
        })
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true;
        return data.typeName.indexOf(value) !== -1;
      },
      // 节点单击事件
      handleNodeClick(data) {
        if(data.parentId != '0' && data.typeId != '0' ){
          this.isShow = true
          this.getRoleTree()
        } else {
          this.isShow = false
        }
        // 专题id
        this.queryParams.typeId = data.typeId
        // 父级id
        this.queryParams.parentId = data.parentId
        // 专题名称
        this.queryParams.typeName = data.typeName
      },
      // 获取角色树
      getRoleTree() {
        deptUserTree().then(response => {
          this.roleTree = response.data;
          // 重命名树结构中的字段
          this.roleTree.forEach(node => {
            this.appendUser(node);
          });
        });
      },
      /** 查询部门下拉树结构 */
      getDeptTreePost() {
        deptTreeSelect().then(response => {
          this.deptOption = response.data;
        });
      },
      appendUser(node) {
        if (node.children && node.children.length > 0) {
          node.children.forEach(child => {
            this.appendUser(child);
          });
        }
        if (node.userChildren && node.userChildren.length > 0) {
          node.children = [...(node.children || []), ...node.userChildren];
          delete node.userChildren;
        }
      },

      // 角色树
      roleClick(data) {
        var flag = this.traverse(data, this.deptOption[0])
        if(flag == false) {
          this.userId = data.id
          this.userName = data.label
        }
      },
      traverse(node, dept) {
        if(dept.id == node.id) {
          this.$message({ message: '选择的数据是部门节点,请选择人员节点', type: 'warning' })
          return true;
        }
        if(dept.children) {
          for(let child of dept.children) {
            if(this.traverse(node, child)) {
              return true;
            }
          }
        }
        return false;
      },
      // 保存权限
      save() {
        console.log(this.userId)
        if(this.userId == undefined) {
          this.$message({ message: '请选择一名人员进行授权操作', type: 'warning' })
        } else {
          this.$modal.confirm('是否确认将"'+ this.queryParams.typeName +'"授权给"'+ this.userName +'"？').then(function () { }).then(() => {
            updateCode({
              typeId: this.queryParams.typeId,
              userId: this.userId
            }).then(response=>{
              this.$modal.msgSuccess('授权成功')
            })
          }).catch(() => { });
        }
      },

      reset() {
        this.form = {
          coverPath: undefined,
          typeName: undefined,
          remark: undefined
        }
        this.directoryForm = {
          typeName: undefined,
          remark: undefined
        }
        this.$nextTick(() => {
          if (this.$refs.textareaFormRef != undefined) {
            this.$refs.textareaFormRef.$refs.textarea.style.height = 'auto'; // 重置高度
          }
          if (this.$refs.directoryFormText != undefined) {
            this.$refs.directoryFormText.$refs.textarea.style.height = 'auto'; // 重置高度
          }
        });
      },
      // 树节点新增
      treeHandleAdd() {
        this.reset()
        if(this.queryParams.typeId == '0') {
          this.resetForm('form')
          this.open = true
          this.title = '添加专题'
          this.dialogImageUrl = ''
        } else {
          this.resetForm('directoryForm')
          this.directoryOpen = true
          this.directoryTitle = '添加目录'
        }
      },
      // 树节点修改
      treeHandleUpdate() {
        this.reset()
        if(this.queryParams.typeId == '0') {
          this.$message({ message: '请选择除根节点专题库以外的节点进行修改', type: 'warning' })
        } else {
          if(this.queryParams.parentId == '0') {
            this.resetForm('form')
            getCodeDetail(this.queryParams.typeId).then(response=>{
              this.form = response.data
              if (response.data.coverPath != null) {
                axios({
                  method: 'POST',
                  url: process.env.VUE_APP_BASE_API + `/archive/special/subject/preview`,
                  params: {
                    id: response.data.typeId,
                    type: '1'
                  },
                  headers: {
                    Authorization: "Bearer " + getToken()
                  },
                  responseType: 'blob' // 更改responseType类型为 blob
                }).then(res => {
                  const blob = new Blob([res.data], {
                    type: "image/jpeg",
                  })
                  this.dialogImageUrl = window.URL.createObjectURL(blob)
                  this.open = true
                  this.title = '修改专题'
                }).catch(err => {
                  console.log(err)
                })
              } else {
                this.dialogImageUrl = ''
                this.open = true
                this.title = '修改专题'
              }
            })
          } else {
            this.resetForm('directoryForm')
            getCodeDetail(this.queryParams.typeId).then(response=>{
              this.directoryForm = response.data
              this.directoryOpen = true
              this.directoryTitle = '修改目录'
            })
          }
        }
      },
      // 保存专题
      submitForm() {
        this.$refs["form"].validate(valid => {
          if(valid) {
            if(this.form.typeId != undefined) {
              updateCode(this.form).then(response=>{
                this.$modal.msgSuccess('修改成功')
                this.open = false
                this.getDeptTree()
                this.isShow = false
                this.fileList = []
                this.typeName = undefined
              })
            } else {
              this.form.parentId = this.queryParams.typeId
              addCode(this.form).then(response=>{
                this.$modal.msgSuccess('新增成功')
                this.open = false
                this.getDeptTree()
                this.isShow = false
                this.fileList = []
                this.typeName = undefined
              })
            }
          }
        })
      },

      // 保存目录
      submitdirectoryForm() {
        this.$refs["directoryForm"].validate(valid => {
          if(valid) {
            if(this.directoryForm.typeId != undefined) {
              updateCode(this.directoryForm).then(response=>{
                this.$modal.msgSuccess('修改成功')
                this.directoryOpen = false
                this.getDeptTree()
                this.isShow = false
                this.typeName = undefined
              })
            } else {
              this.directoryForm.parentId = this.queryParams.typeId
              addCode(this.directoryForm).then(response=>{
                this.$modal.msgSuccess('新增成功')
                this.directoryOpen = false
                this.getDeptTree()
                this.isShow = false
                this.typeName = undefined
              })
            }
          }
        })
      },
      cancel() {
        this.open = false
        this.directoryOpen = false
        this.fileList = []
      },
      treeHandleDelete() {
        if(this.queryParams.typeId == '0') {
          this.$message({ message: '请选择除根节点专题库以外的节点进行删除', type: 'warning' })
        } else {
          const typeId = this.queryParams.typeId
          this.$modal.confirm('是否确认删除专题名称为"' + this.queryParams.typeName + '"的数据项？').then(function() {
            return deleteCode(typeId)
          }).then(() => {
            this.getDeptTree();
            this.isShow = false
            this.typeName = undefined
            this.$modal.msgSuccess("删除成功");
          }).catch(() => {});
        }
      },


      // 文件状态发生改变
      uploadChange(file) {
        const isIMAGE =
          file.raw.type === "image/jpeg" ||
          file.raw.type === "image/png" ||
          file.raw.type === "image/jpg" ||
          file.raw.type === "image/gif";

        if (!isIMAGE) {
          this.$message.error("上传文件只能是图片格式!");
          return false;
        }
      },
      //文件上传成功时的钩子
      handleUploadSuccess(res, file) {
        if(res.code == 200) {
          this.form.coverPath = res.data.url
          this.dialogImageUrl = URL.createObjectURL(file.raw);
        }
      },
      // 文件删除
      handleRemove(file, fileList) {
        console.log(file, fileList);
        var filePath = file.response.data.url
        removeFile({filePath: filePath}).then(response=>{
          console.log(response)
          this.dialogImageUrl = ''
          this.fileList = []
        })
      },
      // 文件个数超出
      handleExceed() {
        this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
      },
    }
  }
  </script>

  <style lang="scss" scoped>
  .avatar-uploader {
    //border: 1px dashed #d9d9d9;
    border-radius: 6px;
    width: 148px;
    height: 148px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }
  .avatar {
    width: 148px;
    height: 148px;
    display: block;
  }

  </style>
